import Interceptor from './Interceptor'

let methods = ['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']
/**
 * Http构造器
 * @param options 参数格式：{header: 请求头}
 * @constructor
 */
export default function Http(options = {
	header: {}
}) {
	this.header = options.header
	this.interceptors = {
		request: new Interceptor(),
		response: new Interceptor()
	}
}

mixinRequestMethods()

function mixinRequestMethods() {
	methods.forEach((method) => {
		let _method = method.toLowerCase()
		Http.prototype[_method] = function(url, data, options) {
			// 组装wx.request需要的参数
			let params = Object.assign({}, options, {
				url,
				data,
				method,
				header: this.header
			})
			return request.call(this, params)
		}
	})
}

function request(options) {
	// 请求前拦截器
	options = this.interceptors.request.intercept(options)
	let _this = this
	return new Promise((resolve, reject) => {
		let reqOptions = Object.assign({}, options, {
			success: (data) => {
				resolve(data)
			},
			fail: (err) => {
				_this.interceptors.request.onError(err)
				reject(err)
			}
		})
		uni.request(reqOptions)
	}).then((res) => {
		// 请求后拦截器
		res = this.interceptors.response.intercept(res)

		return res
	}).catch(err => {
		if (err && err.errMsg === 'request:fail ') {
			// uni.showToast({ '网络错误', 2000, false, 'none' });
		}
	})
}